/*
 * RemoveNullFilterInputStream.java
 *
 * Created on March 24, 2005, 9:44 PM
 */

package util;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author Keith
 */
public class RemoveNullFilterInputStream extends FilterInputStream {
  
  /** Creates a new instance of RemoveNullFilterInputStream */
  public RemoveNullFilterInputStream( InputStream is ) {
    super( is );
  }
  
  public int read( byte[] buf, int from, int len ) throws IOException {
    int bytesToRead = len;
    int bytesRead = 0;
    int cnt = 0;

    while ( bytesToRead > 0 &&
            ( bytesRead = in.read( buf, from, bytesToRead ) ) != -1 ){

      int last = from;
      for ( int i = from; i < from + bytesRead; i++ ){
        if ( buf[ i ] != 0 ){
          if ( last != i ){
            buf[ last ] = buf[ i ];
          }
          last++;
        }
      }
      cnt += ( last - from );
      from = last;
      bytesToRead -= cnt;
    }

    return ( cnt == 0 && bytesRead == -1 ) ? -1 : cnt;
  }

  public int read() throws IOException {
    byte[] buf = new byte[ 1 ];

    int result = read( buf );

    return result == -1 ? result : buf[ 0 ];
  }
}
